package campus.aiit.ssl.manage.custom.dao;

import campus.aiit.ssl.util.RoleUtil;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

/**
 * @author ihaokun
 * @date 2019/12/4 17:44
 */
public class DaoInvocationHandler implements InvocationHandler {
  private Object subject;

  public DaoInvocationHandler(Object subject) {
    this.subject = subject;
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) {
    // args set dynamically
    Parameter[] parameters = method.getParameters();
    for (int i = 0; i < parameters.length; i++) {
      if ("ifUserId".equals(parameters[i].getName())){
        try {
          args[i] = RoleUtil.currentUserIdOfDao();
        } catch (Throwable throwable) {
          throwable.printStackTrace();
        }
      }
    }
    // invoke
    Object result = null;
    try {
      result = method.invoke(subject, args);
    } catch (IllegalAccessException | InvocationTargetException e) {
      e.printStackTrace();
    }
    // result check
    if (method.getAnnotation(DaoResultCheck.class) != null){
      if ((int)result != 1){
        throw new DaoResultException("根据主键操作影响的rows不为1");
      }
    }
    return result;
  }
}